"""
智能体管理器 - 统一管理所有智能体的生命周期
负责智能体的注册、初始化、调度和监控
"""

import asyncio
from typing import Dict, List, Any, Optional, Type
from datetime import datetime

from ..core.interfaces import AgentInterface, ToolInterface
from ..core.events import EventEmitter
from ..core.container import container

from .base_agent import BaseAgent, agent_registry
from .orchestrator.main_orchestrator import MainOrchestrator
from .specialists.resume_analyst import ResumeAnalystAgent
from .specialists.background_checker import BackgroundCheckerAgent  
from .specialists.potential_assessor import PotentialAssessorAgent
from .specialists.code_evaluator import CodeEvaluatorAgent
from .specialists.potential_predictor import PotentialPredictorAgent


class AgentManager(EventEmitter):
    """智能体管理器"""
    
    def __init__(self):
        super().__init__()
        self.orchestrator: Optional[MainOrchestrator] = None
        self.specialists: Dict[str, BaseAgent] = {}
        self.tools: Dict[str, ToolInterface] = {}
        self._initialized = False
        
        # 预定义的智能体类型
        self.agent_classes = {
            "resume_analyst": ResumeAnalystAgent,
            "background_checker": BackgroundCheckerAgent,
            "potential_assessor": PotentialAssessorAgent,
            "code_evaluator": CodeEvaluatorAgent,
            "potential_predictor": PotentialPredictorAgent
        }
    
    async def initialize(self):
        """初始化智能体管理器"""
        if self._initialized:
            return
        
        try:
            await self.emit("agent_manager_initialization_started", {})
            
            # 1. 初始化总调度器
            self.orchestrator = MainOrchestrator()
            await self.orchestrator.initialize()
            
            # 2. 初始化专家智能体
            await self._initialize_specialists()
            
            # 3. 注册智能体到调度器
            await self._register_agents_to_orchestrator()
            
            # 4. 初始化工具
            await self._initialize_tools()
            
            # 5. 注册工具到智能体
            await self._register_tools_to_agents()
            
            self._initialized = True
            
            await self.emit("agent_manager_initialized", {
                "orchestrator_ready": self.orchestrator is not None,
                "specialists_count": len(self.specialists),
                "tools_count": len(self.tools)
            })
            
        except Exception as e:
            await self.emit_error("agent_manager_initialization", e)
            raise
    
    async def _initialize_specialists(self):
        """初始化专家智能体"""
        try:
            # 并行初始化所有专家智能体
            initialization_tasks = []
            
            for agent_name, agent_class in self.agent_classes.items():
                agent_instance = agent_class()
                self.specialists[agent_name] = agent_instance
                initialization_tasks.append(agent_instance.initialize())
            
            # 等待所有智能体初始化完成
            await asyncio.gather(*initialization_tasks)
            
            await self.emit("specialists_initialized", {
                "initialized_agents": list(self.specialists.keys())
            })
            
        except Exception as e:
            await self.emit_error("specialists_initialization", e)
            raise
    
    async def _register_agents_to_orchestrator(self):
        """将智能体注册到调度器"""
        try:
            for agent_name, agent_instance in self.specialists.items():
                self.orchestrator.register_agent(agent_instance)
                agent_registry.register_agent(agent_instance)
            
            await self.emit("agents_registered_to_orchestrator", {
                "registered_count": len(self.specialists)
            })
            
        except Exception as e:
            await self.emit_error("agent_registration", e)
            raise
    
    async def _initialize_tools(self):
        """初始化工具"""
        try:
            # 这里可以初始化各种工具
            # 暂时留空，等待工具实现
            
            await self.emit("tools_initialized", {
                "tools_count": len(self.tools)
            })
            
        except Exception as e:
            await self.emit_error("tools_initialization", e)
            raise
    
    async def _register_tools_to_agents(self):
        """将工具注册到智能体"""
        try:
            # 为每个智能体注册相关工具
            for tool_name, tool_instance in self.tools.items():
                # 注册到调度器
                self.orchestrator.register_tool(tool_instance)
                
                # 注册到相关的专家智能体
                for agent_instance in self.specialists.values():
                    agent_instance.register_tool(tool_instance)
            
            await self.emit("tools_registered_to_agents", {
                "tools_distributed": len(self.tools)
            })
            
        except Exception as e:
            await self.emit_error("tool_registration", e)
            raise
    
    def get_orchestrator(self) -> Optional[MainOrchestrator]:
        """获取总调度器"""
        return self.orchestrator
    
    def get_specialist(self, agent_name: str) -> Optional[BaseAgent]:
        """获取专家智能体"""
        return self.specialists.get(agent_name)
    
    def list_specialists(self) -> List[str]:
        """列出所有专家智能体"""
        return list(self.specialists.keys())
    
    def get_tool(self, tool_name: str) -> Optional[ToolInterface]:
        """获取工具"""
        return self.tools.get(tool_name)
    
    def list_tools(self) -> List[str]:
        """列出所有工具"""
        return list(self.tools.keys())
    
    async def add_specialist(self, agent_name: str, agent_class: Type[BaseAgent], **kwargs):
        """动态添加专家智能体"""
        try:
            if agent_name in self.specialists:
                raise ValueError(f"Agent {agent_name} already exists")
            
            # 创建并初始化智能体
            agent_instance = agent_class(**kwargs)
            await agent_instance.initialize()
            
            # 注册智能体
            self.specialists[agent_name] = agent_instance
            
            if self.orchestrator:
                self.orchestrator.register_agent(agent_instance)
            
            agent_registry.register_agent(agent_instance)
            
            # 为新智能体注册工具
            for tool_instance in self.tools.values():
                agent_instance.register_tool(tool_instance)
            
            await self.emit("specialist_added", {
                "agent_name": agent_name,
                "agent_class": agent_class.__name__
            })
            
        except Exception as e:
            await self.emit_error("add_specialist", e)
            raise
    
    async def remove_specialist(self, agent_name: str):
        """移除专家智能体"""
        try:
            if agent_name not in self.specialists:
                raise ValueError(f"Agent {agent_name} not found")
            
            # 移除智能体
            del self.specialists[agent_name]
            
            await self.emit("specialist_removed", {
                "agent_name": agent_name
            })
            
        except Exception as e:
            await self.emit_error("remove_specialist", e)
            raise
    
    async def add_tool(self, tool_name: str, tool_instance: ToolInterface):
        """动态添加工具"""
        try:
            if tool_name in self.tools:
                raise ValueError(f"Tool {tool_name} already exists")
            
            # 初始化工具
            await tool_instance.initialize()
            
            # 注册工具
            self.tools[tool_name] = tool_instance
            
            # 将工具注册到调度器和所有智能体
            if self.orchestrator:
                self.orchestrator.register_tool(tool_instance)
            
            for agent_instance in self.specialists.values():
                agent_instance.register_tool(tool_instance)
            
            await self.emit("tool_added", {
                "tool_name": tool_name
            })
            
        except Exception as e:
            await self.emit_error("add_tool", e)
            raise
    
    async def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        try:
            status = {
                "initialized": self._initialized,
                "orchestrator_status": None,
                "specialists_status": {},
                "tools_status": {},
                "timestamp": datetime.now().isoformat()
            }
            
            # 获取调度器状态
            if self.orchestrator:
                status["orchestrator_status"] = await self.orchestrator.get_orchestrator_status()
            
            # 获取专家智能体状态
            for agent_name, agent_instance in self.specialists.items():
                try:
                    agent_metrics = await agent_instance.get_agent_metrics()
                    status["specialists_status"][agent_name] = agent_metrics
                except Exception as e:
                    status["specialists_status"][agent_name] = {"error": str(e)}
            
            # 获取工具状态
            for tool_name, tool_instance in self.tools.items():
                status["tools_status"][tool_name] = {
                    "name": tool_instance.name,
                    "available": True
                }
            
            return status
            
        except Exception as e:
            await self.emit_error("get_system_status", e)
            return {"error": str(e), "initialized": False}
    
    async def health_check(self) -> Dict[str, Any]:
        """健康检查"""
        try:
            health_status = {
                "overall_health": "healthy",
                "components": {
                    "orchestrator": "healthy" if self.orchestrator else "not_initialized",
                    "specialists": {},
                    "tools": {}
                },
                "issues": [],
                "timestamp": datetime.now().isoformat()
            }
            
            # 检查专家智能体健康状态
            for agent_name, agent_instance in self.specialists.items():
                try:
                    # 简单的健康检查：尝试获取指标
                    await agent_instance.get_agent_metrics()
                    health_status["components"]["specialists"][agent_name] = "healthy"
                except Exception as e:
                    health_status["components"]["specialists"][agent_name] = "unhealthy"
                    health_status["issues"].append(f"Agent {agent_name}: {str(e)}")
            
            # 检查工具健康状态
            for tool_name in self.tools.keys():
                health_status["components"]["tools"][tool_name] = "healthy"
            
            # 判断整体健康状态
            if health_status["issues"]:
                health_status["overall_health"] = "degraded" if len(health_status["issues"]) < len(self.specialists) / 2 else "unhealthy"
            
            return health_status
            
        except Exception as e:
            await self.emit_error("health_check", e)
            return {
                "overall_health": "unhealthy",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }
    
    async def shutdown(self):
        """关闭智能体管理器"""
        try:
            await self.emit("agent_manager_shutdown_started", {})
            
            # 清理所有组件
            # 注意：这里只是标记，实际的资源清理可能需要更复杂的逻辑
            
            self._initialized = False
            
            await self.emit("agent_manager_shutdown_completed", {})
            
        except Exception as e:
            await self.emit_error("agent_manager_shutdown", e)
            raise


# 全局智能体管理器实例
agent_manager = AgentManager()